﻿using System.Collections.Generic;
using System.Linq;
using LinFu.IoC.Configuration;
using LinFu.IoC.Interfaces;
using LinFu.IoC;
namespace CoreEx.Database.Client.Implementation
{
    /// <summary>
    /// Gets the <see cref="DbConnectionInfo"/> instance associated with the <see cref="IFactoryRequest.ServiceName"/>.
    /// </summary>
    [Factory(typeof(DbConnectionInfo))]
    public class DbConnectionInfoFactory : IFactory<DbConnectionInfo>
    {
        /// <summary>
        /// Gets a <see cref="DbConnectionInfo"/> based on the <see cref="IFactoryRequest.ServiceName"/>
        /// </summary>
        /// <param name="request">The <see cref="IFactoryRequest"/> instance that describes the requested service.</param>
        /// <returns><see cref="DbConnectionInfo"/></returns>
        public DbConnectionInfo CreateInstance(IFactoryRequest request)
        {
            var connectionInfoProvider = request.Container.GetService<IDbConnectionInfoProvider>();
            var connections = connectionInfoProvider.GetConnections();
            
            if (ShouldReturnDefaultConnection(request.ServiceName))
                return GetDefaultConnection(request.Container, connections);
            
            return connections.Where(c => c.Name == request.ServiceName).FirstOrDefault();
        }
        
        private static bool ShouldReturnDefaultConnection(string connectionName)
        {
            return string.IsNullOrEmpty(connectionName);
        }

        private static DbConnectionInfo GetDefaultConnection(IServiceContainer serviceContainer, IEnumerable<DbConnectionInfo> connectionCandidates)
        {
            var defaultConnection =  serviceContainer.GetService<IDefaultConnection>();
            return defaultConnection.Selector(connectionCandidates);
        }

    }
}
